package com.atguigu.yygh.order.service.impl;


import com.alibaba.fastjson.JSONObject;
import com.atguigu.yygh.consts.MqConst;
import com.atguigu.yygh.enums.OrderStatusEnum;
import com.atguigu.yygh.exception.YyghException;
import com.atguigu.yygh.hosp.client.ScheduleFeignClient;
import com.atguigu.yygh.model.order.OrderInfo;
import com.atguigu.yygh.model.user.Patient;
import com.atguigu.yygh.order.mapper.OrderInfoMapper;
import com.atguigu.yygh.order.service.OrderInfoService;
import com.atguigu.yygh.order.utils.HttpRequestHelper;
import com.atguigu.yygh.serice.RabbitService;
import com.atguigu.yygh.user.client.PatientFeignClient;
import com.atguigu.yygh.vo.hosp.ScheduleOrderVo;
import com.atguigu.yygh.vo.msm.MsmVo;
import com.atguigu.yygh.vo.order.OrderCountQueryVo;
import com.atguigu.yygh.vo.order.OrderCountVo;
import com.atguigu.yygh.vo.order.OrderMqVo;
import com.atguigu.yygh.vo.order.OrderQueryVo;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.joda.time.DateTime;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.awt.*;
import java.util.*;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * 订单表 服务实现类
 * </p>
 *
 * @author atguigu
 * @since 2025-03-26
 */
@Service
public class OrderInfoServiceImpl extends ServiceImpl<OrderInfoMapper, OrderInfo> implements OrderInfoService {
    @Autowired
    private OrderInfoMapper orderInfoMapper;
    @Autowired
    private ScheduleFeignClient scheduleFeignClient;
    @Autowired
    private PatientFeignClient patientFeignClient;
    @Autowired
    private RabbitService rabbitService;
    @Override
    public Long submitOrder(String scheduleId, Long patientId) {
        //1.根据scheduleId查询排班信息
        ScheduleOrderVo scheduleOrderVo = scheduleFeignClient.getScheduleOrderVo(scheduleId);
        DateTime dateTimeNow = new DateTime(new Date());
        if (dateTimeNow.isAfter(new DateTime(scheduleOrderVo.getStopTime()))){
            throw new YyghException(20001, "当天预约时间已过");
        }
        //2.根据patientId查询患者信息
        Patient patientInfo = patientFeignClient.getPatientInfo(patientId);
        //3.请求第三方医院接口,获取医院返回的数据
        HashMap<String, Object> paraMap = new HashMap<>();
        paraMap.put("hoscode",scheduleOrderVo.getHoscode());
        paraMap.put("depcode",scheduleOrderVo.getDepcode());
        paraMap.put("hosScheduleId",scheduleOrderVo.getHosScheduleId());
        paraMap.put("reserveDate",scheduleOrderVo.getReserveDate());
        paraMap.put("reserveTime",scheduleOrderVo.getReserveTime());
        paraMap.put("amount",scheduleOrderVo.getAmount());
        JSONObject jsonObject = HttpRequestHelper.sendRequest(paraMap, "http://localhost:9998/order/submitOrder");
        if(null != jsonObject && 200 == jsonObject.getIntValue("code")) {

            OrderInfo orderInfo = new OrderInfo();
            JSONObject data = jsonObject.getJSONObject("data");
            //预约记录唯一标识（医院预约记录主键）
            orderInfo.setHosRecordId(data.getString("hosRecordId"));
            //预约号序
            orderInfo.setNumber((data.getInteger("number")));
            //取号时间
            //Thu Apr 03 00:00:00 CST 202509:00前
            String fetchTime = data.getString("fetchTime");

            orderInfo.setFetchTime(fetchTime);
            //取号地址
            orderInfo.setFetchAddress(data.getString("fetchAddress"));
            //排班剩余预约数
            Integer availableNumber = data.getInteger("availableNumber");
            BeanUtils.copyProperties(scheduleOrderVo,orderInfo);
            orderInfo.setScheduleId(scheduleOrderVo.getHosScheduleId());
            orderInfo.setUserId(patientInfo.getUserId());
            orderInfo.setPatientName(patientInfo.getName());
            orderInfo.setPatientPhone(patientInfo.getPhone());
            //订单交易号
            String orderNo =System.currentTimeMillis()+""+new Random().nextInt(100);
            orderInfo.setOutTradeNo(orderNo);
            orderInfo.setPatientId(patientId);
            //0-未支付，1-已支付，2-已取号,-1-取消订单
            orderInfo.setOrderStatus(OrderStatusEnum.UNPAID.getStatus());
            //保存订单信息
            orderInfoMapper.insert(orderInfo);
            //5 根据医院返回数据，更新排班数量
            //通过rabiitmq消息队列，通知hosp后台更新排班数量
            OrderMqVo orderMqVo = new OrderMqVo();
            orderMqVo.setScheduleId(scheduleId);
            orderMqVo.setAvailableNumber(availableNumber);
            MsmVo msmVo = new MsmVo();
            msmVo.setPhone("18289646811");
            orderMqVo.setMsmVo(msmVo);
            rabbitService.sendMesssage(MqConst.EXCHANGE_DIRECT_ORDER,MqConst.ROUTING_ORDER,orderMqVo);
            return orderInfo.getId();
        } else {
            throw new YyghException(20001, "提交订单失败");
        }

    }

    @Override
    public Page<OrderInfo> getPageList(Integer page, Integer limit, OrderQueryVo orderQueryVo) {
        if (orderQueryVo.getUserId()==null){
            throw new YyghException(20001, "用户id不能为空");
        }
        Page<OrderInfo> page1 = new Page<>(page, limit);
        //封装查询条件
        QueryWrapper<OrderInfo> queryWrapper = getOrderInfoQueryWrapper(orderQueryVo);

        Page<OrderInfo> orderInfoIPage = orderInfoMapper.selectPage(page1,queryWrapper);
        //将pagelist状态转为中文
        orderInfoIPage.getRecords().forEach(orderInfo -> {
            Map<String, Object> param = orderInfo.getParam();
            param.put("orderStatusString",OrderStatusEnum.getStatusNameByStatus(orderInfo.getOrderStatus()));
        });
        return orderInfoIPage;
    }

    @Override
    public OrderInfo selectDetail(Long orderId) {
        OrderInfo orderInfo = orderInfoMapper.selectById(orderId);
        orderInfo.getParam().put("orderStatusString",OrderStatusEnum.getStatusNameByStatus(orderInfo.getOrderStatus()));
        return orderInfo;

    }

    @Override
    public void remindSms() {
        QueryWrapper<OrderInfo> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("reserve_date",new DateTime().toString("yyyy-MM-dd"));
        queryWrapper.ne("order_status",OrderStatusEnum.CANCLE.getStatus());
        List<OrderInfo> orderInfos = orderInfoMapper.selectList(queryWrapper);
        orderInfos.forEach(orderInfo ->{
            //发送短信
            MsmVo msmVo = new MsmVo();
            msmVo.setPhone(orderInfo.getPatientPhone());
            String reserveDate = new DateTime(orderInfo.getReserveDate()).toString("yyyy-MM-dd") + (orderInfo.getReserveTime()==0 ? "上午": "下午");
            Map<String,Object> param = new HashMap<String,Object>(){{
                put("title", orderInfo.getHosname()+"|"+orderInfo.getDepname()+"|"+orderInfo.getTitle());
                put("reserveDate", reserveDate);
                put("name", orderInfo.getPatientName());
            }};
            msmVo.setParam(param);
            rabbitService.sendMesssage(MqConst.EXCHANGE_DIRECT_MSM,MqConst.ROUTING_MSM_ITEM,msmVo);

        });
    }

    @Override
    public Map<String, Object> getStatisticalByDate(OrderCountQueryVo orderCountQueryVo) {
        List<OrderCountVo> orderCountByDate = orderInfoMapper.getOrderCountByDate(orderCountQueryVo);
        List<String> dateList = orderCountByDate.stream().map(OrderCountVo::getReserveDate).collect(Collectors.toList());
        List<Integer> countList = orderCountByDate.stream().map(OrderCountVo::getCount).collect(Collectors.toList());
        Map<String, Object> map = new HashMap<>();
        map.put("dateList", dateList);
        map.put("countList", countList);
        return map;
    }

    private static QueryWrapper<OrderInfo> getOrderInfoQueryWrapper(OrderQueryVo orderQueryVo) {
        QueryWrapper<OrderInfo> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_id", orderQueryVo.getUserId());
        if (!StringUtils.isEmpty(orderQueryVo.getPatientId())){
            queryWrapper.eq("patient_id", orderQueryVo.getPatientId());
        }
        if (!StringUtils.isEmpty(orderQueryVo.getPatientName())){
            queryWrapper.like("patient_name", orderQueryVo.getPatientName());
        }
        //医院名称
        if (!StringUtils.isEmpty(orderQueryVo.getKeyword())){
            queryWrapper.like("hosname", orderQueryVo.getKeyword());
        }
        //订单状态
        if (!StringUtils.isEmpty(orderQueryVo.getOrderStatus())){
            queryWrapper.eq("order_status", orderQueryVo.getOrderStatus());
        }
        //安排时间
        if (!StringUtils.isEmpty(orderQueryVo.getReserveDate())){
            queryWrapper.ge("reserve_date",orderQueryVo.getReserveDate());//大于等于
        }
        if(!StringUtils.isEmpty(orderQueryVo.getCreateTimeBegin())){
            queryWrapper.ge("create_time",orderQueryVo.getCreateTimeBegin());
        }
        if(!StringUtils.isEmpty(orderQueryVo.getCreateTimeEnd())){
            queryWrapper.le("create_time",orderQueryVo.getCreateTimeEnd());//小于等于
        }
        return queryWrapper;
    }
}
